package com.question.java.time.exec04;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Description: java.util.Date转换成java.time.LocalDate
 * 问题：用户希望将java.util.Date或java.util.Calendar转换成java.time.LocalDate包中相应的类
 * 方案：转换既可以使用Instant作为中介，也可以使用java.sql.Date或java.sql.Timestamp,也可使用整数或字符串
 * @Author: Jun Yang
 */
public class DateTimeExample18 {

    // 方案一：使用Instant作为中介，将java.util.Date转换成java.time.LocalDate
    public static LocalDate convertFromUtilDateUsingInstant(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    // 方案二：介由java.sql.Date,将java.util.Date转换成java.time.LocalDate
    public static LocalDate convertFromUtilDateUsingSqlDate(Date date) {
        return new java.sql.Date(date.getTime()).toLocalDate();
    }

    // 方案三：经过格式化的字符串，将java.util.Date解析成LocalDateTime
    public static LocalDateTime convertFromUtilDateToLDTUsingString(Date date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        return LocalDateTime.parse(df.format(date), DateTimeFormatter.ISO_DATE_TIME);
    }

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("date: " + date);
        LocalDate localDate1 = convertFromUtilDateUsingInstant(date);
        System.out.println("localdate1: " + localDate1);

        LocalDate localDate2 = convertFromUtilDateUsingSqlDate(date);
        System.out.println("localdate2: " + localDate2);

        LocalDateTime localDateTime = convertFromUtilDateToLDTUsingString(date);
        System.out.println("localtime: " + localDateTime);
    }
}
